package com.sy.rabbitmq.return_listener;

import com.rabbitmq.client.*;
import com.sy.rabbitmq.TestProperties;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 消息返回机制 -return  生产端
 */
public class Producer {
    public static void main(String[] args) throws IOException, TimeoutException {
        // 创建ConnectionFactory
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(TestProperties.getIp());
        factory.setPort(TestProperties.getPort());
        factory.setVirtualHost("/");

        //2.获取Connection
        Connection connection = factory.newConnection();

        //3.获取channel
        Channel channel = connection.createChannel();

        //4.指定消息的投递模式: confirmSelect: 消息的确认模式
        channel.confirmSelect();

        String exchangeName = "test_confirm_exchange";
        String routeKey = "save";

        //5.发送一条消息
        String msg = "Hello RabbitMQ send confirm message!";
        //6.添加一个错误路由监听-防止消息未送达
        channel.addReturnListener(
                new ReturnListener() {
                    @Override
                    public void handleReturn(
                        int replyCode,
                        String replyText,
                        String exchange,
                        String routingKey,
                        AMQP.BasicProperties properties,
                        byte[] body
                    ) throws IOException {
                        System.out.println("-------------return无法路由消息--------------");
                    }
                }
        );
        channel.basicPublish(exchangeName,routeKey,true,null,msg.getBytes());
    }
}
